<template>
  <div>
    <!--搜索区域-->
    <el-card class="search-card">
      <!--搜索表单
        ref是表单的引用名称，用于表单校验和表单重置，需要这个名字
        rules是表单校验规则,暂时没有校验,可以删除不写
        model是表单数据模型，用于绑定表单数据
      -->
      <el-form ref="searchUser" size="small " :inline="true" :model="searchUser" label-width="80px">
        <!--prop是表单校验和重置需要的绑定变量名,且这个名字和绑定变量名一致-->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="searchUser.username" style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="searchUser.phone" style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="注册时间" prop="searchTime">
          <!--value-format是日期格式-->
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="searchUser.searchTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" type="primary" @click="onSearch">搜索</el-button>
          <!--@click是点击事件，resetForm是重置方法，searchUser是表单引用名称-->
          <el-button size="mini" @click="resetForm('searchUser')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <!--批量删除按钮-->
      <el-button size="mini" type="danger" @click="handleDeleteAll">
        <i class="el-icon-delete"></i>批量删除
      </el-button>
      <!--添加按钮-->
      <el-button size="mini" type="primary" @click="handleAdd">
        <i class="el-icon-plus"></i>添加
      </el-button>
      <!--表格区域-->
      <el-table
          :data="tableData"
          @selection-change="handleSelectionChange"
          style="width: 100%">
        <!--多选框-->
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <!--每个列,prop是后端返回数据的属性-->
        <el-table-column
            prop="id"
            label="ID"
            width="100">
        </el-table-column>
        <el-table-column
            prop="username"
            label="用户名"
            width="100">
        </el-table-column>
        <!--        // 密码列-->
        <el-table-column
            prop="password"
            label="密码"
            width="150">
        </el-table-column>
        <!--        // 手机号列-->
        <el-table-column
            prop="phone"
            label="手机号"
            width="150">
        </el-table-column>
        <!--        //注册时间列-->
        <el-table-column
            prop="createTime"
            label="注册时间"
            width="150">
        </el-table-column>
        <!--        // 余额列-->
        <el-table-column
            prop="money"
            label="余额"
            width="100">
        </el-table-column>
        <!--        // 性别列-->
        <el-table-column
            prop="sex"
            label="性别"
            width="100">
          <template slot-scope="scope">
            <el-tag
                :type="scope.row.sex == '1' ? 'primary' : 'success'"
                disable-transitions>{{ scope.row.sex == '1' ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <!--        // 角色列-->
        <el-table-column
            prop="roleName"
            label="角色"
            width="100">
        </el-table-column>
        <!--操作列-->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">编辑
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[3, 6, 10]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </el-card>
    <!--新增用户弹窗-->
    <el-dialog
        :title=title
        :visible.sync="dialogFormVisible"
        width="30%">
      <!--表单-->
      <el-form label-position="left" :rules="rules" ref="addUserForm" :model="addUserForm" label-width="80px">
        <!--用户名标签-->
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <!--密码标签-->
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" show-password placeholder="请输入密码"></el-input>
        </el-form-item>
        <!--手机号列-->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addUserForm.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <!--性别列-->
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="addUserForm.sex">
            <el-radio label='1'>男</el-radio>
            <el-radio label='2'>女</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--余额列-->
        <el-form-item label="余额" prop="money">
          <el-input v-model="addUserForm.money" placeholder="请输入余额"></el-input>
        </el-form-item>
      </el-form>
      <div v-if="type==='add'" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('addUserForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
      <div v-if="type==='update'"  slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateForm('addUserForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: "UserView",
  data() {
    // 自定义表单验证
    const validatePhone = (rule, value, callback) => {
      if (value=== '') {
        callback(new Error('请输入手机号码'));
      } else if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };
    const validateMoney = (rule, value, callback) => {
      if (value=== '') {
        callback(new Error('请输入金额'));
      } else if (!/^[1-9]\d*$/.test(value)) {
        callback(new Error('请输入正确的金额'));
      } else {
        callback();
      }
    };
    return {
      type:'',
      title: '',
      searchUser: {
        username: '',
        phone: '',
        searchTime: '',
        beginTime: '',
        endTime: ''
      },
      tableData: [],
      pageNum: 1,
      pageSize: 3,
      total: null,
      //批量删除存放ids的数组
      idarr: [],
      //添加表单的显示状态--添加表单
      dialogFormVisible: false,
      // 新增用户表单数据
      addUserForm: {
        username: '',
        password: '',
        phone: '',
        sex: '',
        money: ''
      },
      //表单规则
      rules: {
        // 用户名必须填写且不能为空,在2-10个字符之间失去焦点时进行验证
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur'}
        ],
        // 密码必须填写且不能为空,在2-20个字符之间失去焦点时进行验证
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 2, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
        ],
        phone: [
          {validator: validatePhone, trigger: 'blur'}
        ],
        money: [
          {validator: validateMoney, trigger: 'blur'},
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 搜索
    onSearch() {
      //console.log(this.searchUser)
      this.searchUser.beginTime = this.searchUser.searchTime[0]
      this.searchUser.endTime = this.searchUser.searchTime[1]
      console.log(this.searchUser)

      this.fetchData()
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.searchUser.searchTime = ''
      this.searchUser.beginTime = ''
      this.searchUser.endTime = ''
      this.searchUser.username = ''
      this.searchUser.phone = ''
      this.pageNum = 1
      this.pageSize = 3
      this.fetchData()
    },
    // 查询用户列表
    fetchData() {
      axios.get("/user/list", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          username: this.searchUser.username,
          phone: this.searchUser.phone,
          beginTime: this.searchUser.beginTime,
          endTime: this.searchUser.endTime,
        }
      }).then(res => {
        console.log(res.data)
        this.tableData = res.data.list
        this.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    },
    // 分页大小改变时触发
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val
      this.fetchData()
    },
    // 分页当前页改变时触发
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val
      this.fetchData()
    },
    // 编辑按钮点击时触发,获取当前行数据
    handleEdit(index, row) {
      if(this.dialogFormVisible !== true){
        this.dialogFormVisible = true
      }
      if (this.type !== "update"){
        this.title= "修改用户"
        this.type= "update"
      }

      //打印当前行信息,index是位置,row是数据
      console.log(index, row);
      // 打印表单数据
      console.log(this.addUserForm);
      // 打印当前行数据
      this.addUserForm = row
      console.log(row)
      if(row.sex === 1){
        this.addUserForm.sex = '1'
      } else {
        this.addUserForm.sex = '2'
      }
      // 打印addUserForm数据
      console.log(this.addUserForm);
    },
    // 删除按钮点击时触发,获取当前行数据
    handleDelete(index, row) {
      //打印当前行数据
      console.log(row);
      //确认框是否删除
      if (confirm('确定删除吗?')) {
        axios.delete("/user/delete?id=" + row.id).then(res => {
          console.log(res)
          console.log(res.data)
          if (res.code === 200) {
            this.pageNum = 1
            this.fetchData()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        this.$message({
          message: '删除失败',
          type: 'error'
        })
      }
    },
    //获取选中的行数据
    handleSelectionChange(val) {
      console.log(val)
      this.idarr = []
      val.forEach(item => {
        this.idarr.push(item.id)
      })
      console.log(this.idarr)
    },
    // 批量删除按钮
    handleDeleteAll() {

      axios.get("/user/deleteAll?id=" + this.idarr)
          .then(res => {
            if (res.code === 2000) {
              this.pageNum = 1
              this.fetchData()
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            }
          }).catch(err => {
        console.log(err)
      })

    },
    //添加按钮
    handleAdd() {
      this.addUserForm= {
        username: '',
        password: '',
        phone: '',
        sex: '',
        money: ''
      }
      if(this.dialogFormVisible !== true){
        this.dialogFormVisible = true
      }
      if(this.type !=='add'){
        this.type="add"
        this.title='添加用户'
      }

    },
    //表单添加按钮
    submitForm() {
      this.title = '添加用户'
      //校验表单
      this.$refs.addUserForm.validate(valid => {
        if (valid) {
          axios.post('/user/add', this.addUserForm)
              .then(response => {
                console.log(response)
                if (response.code === 2000) {
                  this.$message.success('添加成功');
                  //页数重置为1
                  this.pageNum = 1
                  this.fetchData()
                  //关闭弹窗
                  this.dialogFormVisible = false
                }
              })
        }
        else {
          this.$message.error('请填写正确的信息');
        }
      })
    },
    //表单修改
    updateForm() {
      axios.post('/user/update', this.addUserForm)
          .then(response => {
            console.log(response)
            if (response.code === 2000) {
              this.$message.success('修改成功');
              //页数重置为1
              this.pageNum = 1
              this.fetchData()
              //关闭弹窗
              this.dialogFormVisible = false
            }
          })
    }
  }
}
</script>

<!-- 添加非 scoped 样式来覆盖 Element UI 默认样式 -->
<style>
.search-card {
  width: 100%;
  height: 70px;
}

.table-card {
  width: 100%;
  height: 480px;
  margin-top: 5px;
}

/* 深色表头样式 */
.el-table .el-table__header-wrapper th {
  background-color: #f8f8f9 !important; /* Element UI 主题色 */
  color: black;
}
</style>